package cn.gqr.dao;

import cn.gqr.entity.Blog;
import cn.gqr.entity.Content;
import cn.gqr.entity.Type;
import com.mongodb.client.result.DeleteResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Repository;

@Repository
public class ContentDao {

    @Autowired
    MongoTemplate mT;

    //根据内容id查找文章内容
    public Content findByContextId(String id){
        Criteria c = new Criteria();
        Content content = mT.findOne(new Query(c.where("id").is(id)), Content.class);
        return content;
    }


    //根据内容id更新文章内容
    public boolean upById(Content content){
        Query q = new Query();
        q.addCriteria(Criteria.where("id").is(content.getId()));
        Update u = new Update().set("documents",content.getDocuments());
        return mT.updateFirst(q,u,Content.class).wasAcknowledged();
    }


    //根据文章id删除文章
    public boolean delById(String id){
        Query q = new Query(Criteria.where("id").is(id));
        return mT.remove(q, Content.class).wasAcknowledged();
    }

    //根据博客id删除文章
    public boolean del(Blog blog){
        Query q = new Query(Criteria.where("id").is(blog.getId()));
        Query q2 = new Query(Criteria.where("id").is(blog.getTextId()));
        Query q3 = new Query(Criteria.where("id").is(blog.getTypeId()));
        //删除博客
        DeleteResult remove = mT.remove(q, Blog.class);
        //删除文章
        mT.remove(q2, Content.class);
        //减少类型数量
        Type t = mT.findOne(q3, Type.class);

        Update p = new Update().set("num", t.getNum() - 1);
        mT.updateFirst(q3,p,Type.class);
        return remove.getDeletedCount()>0;
    }

    //添加文章内容
    public Content addContent(Content content){
        return mT.insert(content);
    }

}
